<template>
	<view v-if="loaded" class="root">
		<!-- <view class="">{{id}}</view> -->
		<view :class="hasComment ? 'blog-container' : 'blog-container c-on-margin'" :key="blog.id">
			<image class="item-head" :src="params.avatarurl" mode="aspectFill"></image>
			<text class="item-title">{{blog.title}}</text>
			<text class="item-time">{{params.nickName}} @{{blog.createTime}}</text>
			<rich-text :nodes="blog.content" class="item-content"></rich-text>
			<!-- <image :src="imgurl" mode="widthFix" class="item-pic"></image> -->
			<text class="icon iconfont icon-biaoqian img-arrow"></text>
			<view class="">
				<text v-for="(tag,index) in blog.tags" class="item-tag">{{tag}}</text>
			</view>
			<view class="icon-container">
				<text @click.stop="onChangeGood(blog,false)" v-if="!hasGood" class="icon iconfont icon-good"></text>
				<text @click.stop="onChangeGood(blog,true)" v-else class="icon iconfont icon-good-fill"></text>
				<text>{{blog.good}}</text>
				<text class="icon iconfont icon-pinglun"></text>
				<text>{{params.cmtCount}}</text>
				<text class="icon iconfont icon-liulan"></text>
				<text>{{blog.readCount}}</text>
			</view>
		</view>
		<view class="comment-container c-on-margin" v-if="hasComment">
			<view class="comment-item" v-for="(c,index) in parents" :key="c.id">
				<image :src="c.avatar" mode="aspectFill" class="comment-avatar"></image>
				<text  class="comment-nickName">{{c.nickName}} <text v-if="canDelete(c)" class="drop" @click="deleteComment(c,true,index)">[删除]</text> </text>
				
				<text class="comment-time">{{c.createTime}}</text>
				<text class="comment-content" @click="clickToReply(c)">{{c.content}}</text>
				<view class="chil-container" v-for="(chil,idx) in replies[index]">
					<text>
						<text class="chil-nickName">{{chil.nickName}} <span class="chil-atNickName">@{{c.nickName}}</span></text>
						<text class="chil-time">{{chil.createTime}}</text>
						<text v-if="canDelete(chil)" class="drop" @click="deleteComment(chil,false,idx)">[删除]</text>
					</text>
					<text class="chil-content" @click="clickToReply(chil)">{{chil.content}}</text>
				</view>
			</view>
		</view>
		<view class="c-on-container">
			<image :src="params.userAvatar" mode="aspectFill" class="c-on-avatar" @click.stop="showLogin"></image>
			<textarea :value="params.inputValue"  :placeholder="params.inputHolder" class="c-on-content" @input="inputGetValue" />
			<text class="c-on-fasong iconfont icon-fasong" @click="pushCmtValue"></text>
		</view>
		<login-dialog ref="login" @afterLogin="afterLogin"></login-dialog>
	</view>
</template>

<script>
import { stdout } from 'process';

	let parentId = null;
	let cmtValue = "";
	let app = getApp();
	export default {
		data() {
			return {
				id:"",
				blog:[],
				params:{
					"imgurl":"",
					"avatarurl":"",
					"cmtCount":0,
					"nickName":"",
					"inputHolder":"请输入评论......",
					"inputValue":"",
					"userAvatar":"../../static/icon/default_user.png"
				},
				parents:[],
				replies:[],
				good_ids:[],
				hasGood:false,
				loaded:false,
				hasComment:false,
			}
		},
		onLoad(options) {
			this.$noti.add(this.$params.noti_login_status,this.afterLogin,this);
			let ids = uni.getStorageSync(this.$params.key_good_ids)
			
			this.good_ids = ids;
			if(this.good_ids.findIndex(e => e.id==options.id)>=0){
				this.hasGood = true;
			}
			this.addReadCount(options.id);
			this.loaded = true;
		},
		onUnload(){
			this.$noti.remove(this.$params.noti_login_status,this);
		},
		mounted() {
			if(!app.globalData.token == 0){
				this.params.userAvatar = this.$params.host + app.globalData.avatar;
			}
			
		},
		methods: {
			onChangeGood(blog,isGood){
				//同步到服务器,并且去最新数据
				let url = this.$params.host + (!isGood ? this.$params.action_blogs_good : this.$params.action_blogs_delgood);
				let data = {
					"id":blog.id,
				}
				this.$request.postParam(url,data,res =>{
					this.blog.good = res.data;
					let blog_data = {
						"picture":blog.picture,
						"id":blog.id,
						"title":blog.title
					}
					if(isGood){
						this.hasGood = !this.hasGood;
						this.good_ids.splice(this.good_ids.indexOf(blog_data),1);
					}else{
						this.hasGood = !this.hasGood;
						this.good_ids.push(blog_data);
					}
					let pages = getCurrentPages();
					let pre = pages[pages.length-2];
					pre.refreshGood(this.good_ids);
					uni.setStorageSync(this.$params.key_good_ids,this.good_ids);
					
				},()=>{
					
				});
			},
			addReadCount(id){
				let url = this.$params.host+this.$params.action_blogs_read;
				let data = {
					"id":id
				}
				this.$request.postParam(url,data,res =>{
					this.blog.readCount = res.data;
					// console.log(id);
					this.$noti.post(this.$params.noti_refresh_count,{
						id:id,
						count:this.blog.readCount,
					})
					
				},()=>{
					// this.refreshPreviousPage(id);
					this.getBlog(id);
				})
			},
			getBlog(id){
				this.$request.get(this.$params.host+this.$params.action_hot+id,res =>{
					this.blog = res.data;
					// console.log(this.blog);
					//因异步数据问题 初步无法显示三层表达式a.b.c  正常页面无问题但控制台报错
					this.params.imgurl = this.$params.host + this.blog.picture;
					this.params.avatarurl = this.$params.host + this.blog.user.avatar;
					this.params.cmtCount = this.blog.comments.length;
					this.params.nickName = this.blog.user.nickName;
					
					this.blog.createTime = this.$util.formatTime(new Date(this.blog.createTime));
					this.blog.content = this.blog.content.replace(/\<img/gi,"<img class='img'");
					uni.setNavigationBarTitle({
						title:this.blog.user.nickName
					})
					// console.log(this.blog.comments);
					
					this.hasComment = true;
					this.formatComments(this.blog.comments);
				},() =>{
					// console.log("wancheng");
				})
			},
			refreshPreviousPage(id){
				//
				let pages = getCurrentPages();
				let pre = pages[pages.length-2];
				pre.refreshCount(id,this.blog.readCount);
			},
			formatComments(comments){
				if(comments.length == 0) return;
				let parents = []
				comments.forEach(c =>{
					if(c.avatar.startsWith("/http")){
						c.avatar = c.avatar.substring(1)
					}else if(!c.avatar.startsWith("http")){
						c.avatar = this.$params.host + c.avatar.substring(1);
					}
					c.createTime = this.$util.formatTime(new Date(c.createTime));
					if(c.parentId == null){
						parents.push(c);
					}
					
					
				})
				parents.sort((c1,c2) =>{
					return new Date(c2.createTime).getTime()- new Date(c1.createTime).getTime();
				});
				
				let replies = new Array(parents.length).fill([]);
				let index = 0
				parents.forEach(r => {
					let cmmts = []
					cmmts = cmmts.concat(this.getChildren(r,comments))
					replies[index++] = cmmts
					comments = comments.filter(c => cmmts.every(cc => cc.id!=c.id))
				})
				this.parents = parents
				this.replies = replies
				// console.log(this.parents);
				// console.log(this.replies);
			},
			getChildren(parent,comments){
				//todo:得到parent所有的子评论
				
				let replies = [];
				let index = 0;
				comments.forEach(c => {
					if(c.parentId == parent.id){
						replies.push(c)
						
						c.toUser = parent.nickName;
						replies.concat(this.getChildren(c,comments))
					}
				})
				return replies;
			},
			clickToReply(item){
				parentId = item.id;
				console.log(parentId);
				console.log(app.globalData.token);
				console.log(app.globalData.uid);
				this.params.inputHolder = "@" + item.nickName
			},
			inputGetValue(e){
				cmtValue = e.detail.value;
			},
			pushCmtValue(){
				if(app.globalData.token.length == 0){
					this.$refs.login.show();
					return;
				}
				if(cmtValue.length == 0){
					uni.showToast({
						title:"还没输入哦",
						icon:'none',
					});
				}
				
				let data ={
					nick_name:app.globalData.nickName,
					avatar:"/" + app.globalData.avatar,
					email:app.globalData.email,
					content:cmtValue,
					blog_id:this.blog.id,
					parent_id:parentId,
					token:app.globalData.token,
					is_owner: app.globalData.uid == this.blog.user.id,
				}
				this.$request.jsonParam(this.$params.host+this.$params.action_blogs_add_comment,data,res=>{
					if(!res.success){
						uni.showToast({
							title:res.message,
							icon:"none"
						})
						return;
					}
					console.log(res);
					let cmt = {};
					cmt.avatar = res.data.avatar;
					cmt.blogId = res.data.blogId;
					cmt.content = res.data.content;
					cmt.createTime = res.data.createTime;
					cmt.email = res.data.email;
					cmt.id = res.data.id;
					cmt.nickName = res.data.nickName;
					cmt.owner = res.data.owner;
					cmt.parentId = res.data.parentId;
					let comments = this.blog.comments.concat(cmt);
					this.blog.comments = comments;
					this.formatComments(comments);
					this.hasComment = this.blog.comments.length>0;
					this.params.inputHolder = "请输入评论......";
					this.params.inputValue = "";
					cmtValue = "";
					parentId = null;
					//刷新列表页的评论数
					this.params.cmtCount = this.blog.comments.length;
					this.$noti.post(this.$params.noti_refresh_comment_count,{
						id:this.blog.id,
						comments:comments,
					})
					
				},()=>{})
				
			},
			showLogin(){
				this.$refs.login.show();
			},
			afterLogin(){
				this.params.userAvatar =this.$params.host + app.globalData.avatar;
				console.log(223332);
			},
			canDelete(c){
				return app.globalData.type == 1 || app.globalData.email == c.email;
				console.log(app.globalData.type == 1 || app.globalData.email == c.email);
			},
			deleteComment(c,isParent,index){
				
				if(app.globalData.token.length==0){
					uni.showToast({
						title:"请先登录",
						icon:"none"
					})
					this.$refs.login.show();
					return;
				}
				
				
				let url = this.$params.host+this.$params.action_blogs_del_comment+c.id ;
				let data={
					token:app.globalData.token
				}
				
				uni.showModal({
					title: '删除评论',
					content: '是否删除评论?\n此评论下的评论也会一同删除',
					showCancel: true,
					cancelText: '取消',
					confirmText: '删除',
					success: res => {
						if(confirm){
							
							this.$request.deleteRequire(url,data,res=>{
								
								if(res.success){
									if(isParent){
										let list = this.replies[index];
										list.push(this.parents[index]);
										this.$util.remove(this.replies,index);
										this.$util.remove(this.parents,index);
										this.blog.comments = this.blog.comments.filter(c => list.every(li => c.id!=li.id));
									}else{
										let children = this.getChildren(c,this.replies);
										children.push(c);
										this.replies[index] = this.replies[index].filter(r => children.every(c => c.id!=r.id));
									}
									this.formatComments(this.parents)
									this.params.cmtCount = this.blog.comments.length;
									this.$noti.post(this.$params.noti_refresh_comment_count,{
										id:this.blog.id,
										comments:this.blog.comments,
									})
								}
								
							},()=>{})
							
							
							
							
						}
					},
					fail: () => {},
					complete: () => {}
				});
			}
		}
	}
</script>

<style>
	@import url("blog.css");
	@import url("../../common/iconfont.css");
</style>
